<template>
    <div class="detail">
        <!-- ----------------商品详情页--------------- -->
        <div class="back-nav-box">
            <back-nav title="商品详情" left-text="返回" left-arrow @navback="navback"></back-nav>
        </div>

      <div class="detail-img">
            <van-image
                width="100%"
                :src="detailData.large_img"
            />
      </div>

      <div class="detail-content">
          <div class="pro-info">
              <div>
                  <div class="zh-name">{{detailData.name}}</div>
                  <div class="en-name">{{detailData.enname}}</div>
              </div>
              <div class="pro-price">&yen;{{detailData.price}}</div>
          </div>
          <!-- 规格 -->
          <div class="pro-rule">
              <div class="pro-rule-item" v-for="(item,index) in detailData.rules" :key="index">
                  <!-- 温度 -->
                  <div class="pro-rule-title" >{{item.title}}</div>
                  <div class="pro-sub-rule">
                      <div  class="pro-sub-rule-item" :class="{active:item.activeIndex===sindex}" v-for="(i,sindex) in item.rules" :key="sindex" @click="dataActiveIndex=item.activeIndex=sindex" >{{i.title}}</div>
                  </div>
              </div>
                    <!-- 糖 -->
               <!-- <div class="pro-rule-item">
                  <div class="pro-rule-title">{{detailData.sugar_desc}}</div>
                  <div class="pro-sub-rule">
                      <div class="pro-sub-rule-item active" v-for="(item,index) in sugar" :key="index">{{item}}</div>
                  </div>
              </div> -->
              
          </div>
          <hr>
          <!-- 数量 -->
          <div class="select-count">
                <div class="select-left">选择数量</div>
               <van-stepper v-model="count" theme="round" button-size="22" disable-input />
          </div>
          <hr>
          <!-- 描述 -->
          <div class="describe">
              <div class="desc-title">商品描述</div>
              <div class="desc-content">
                  <div class="desc-content-item" v-for="(item,index) in detailDesc" :key="index"> {{item}}</div>
                </div>
          </div>
          <!-- 占位（导航） -->
          <div class="sitting"></div>
          <!-- 商品导航 -->
          <van-goods-action>
                <van-goods-action-icon icon="bag" text="购物袋" :badge="shopBag===0?'':shopBag" @click="toShopbag"/>
                <van-goods-action-icon icon="like" :text="isLike?'已收藏':'收藏'" :badge="collect===0?'':collect" :class="isLike?'likeActive':''" :color="isLike?'#0c34ba':''" @click="likeOrNotlike"/>
                <van-goods-action-button color="#2450F2" type="warning" text="加入购物袋" @click="addShopBag"/>
                <van-goods-action-button color="#0C34BA" type="danger" text="立即购买" @click="buyNow"/>
            </van-goods-action>
      </div>
    </div>
</template>

<script>
import BackNav from '../components/BackNav.vue'
export default {
    data() {
        return {
            shopBag:0,//用户加购物车的数量
            collect:0,
            isLike:false,
            pID:'',
            detailData:{},//当前商品的详细数据
            detailDesc:[],//描述信息
            // sugar:[],//糖分
            // tem:[],//温度
            dataActiveIndex:0,
            count:1,//数量
            sid:'',
            isOver:0,//判断请求是否完成
        }
    },
    components:{BackNav},
    created() {
        this.pID=this.$route.params.pID;
        this.getProductDetailById();
        this.findUserLike();
        this.findUserShopbagCount();
    },
    methods: {
        // 点击购物袋跳转至购物袋页面
        toShopbag(){
             this.$router.push({name:'Shopbag'})
        },
        // 点击nav back返回
        navback(){
            this.$router.go(-1)
        },
        getProductDetailById(){
            // 调用商品详情接口
            this.axios({
                methods:'get',
                url:'/productDetail',
                params:{
                    appkey:'U2FsdGVkX19WSQ59Cg+Fj9jNZPxRC5y0xB1iV06BeNA=',
                    pid:this.pID
                }
            }).then(res =>{
                if(res.data.code==600){
                    let data=res.data.result[0];
                    console.log(data);
                    this.detailDesc=data.desc.split(/\n/)
                    // 把规格数据处理成这种模式
                    // [
                    //     {title:'温度',activeIndex:0,rules:[{title:'冷'},{title:'热'}]}
                    // ]
                    let ruleData=['cream','sugar','milk','tem']
                    let rules=[]
                    ruleData.forEach(v=>{
                        if(!data[v]){
                            return
                        }
                        let r={
                            title:data[`${v}_desc`],
                            activeIndex:0,
                            rules:[]
                        }
                        let rs=data[v].split(/\//);
                        rs.forEach(value=>{
                            let subRule={
                                title:value
                            }
                            r.rules.push(subRule)
                        })
                            rules.push(r)
                    })
                    console.log('rules',rules);
                    data.rules=rules;
                    this.detailData=data
                    // console.log(' this.detailData', this.detailData);
                    // this.sugar=this.detailData.sugar.split(/\//)
                    // this.tem=this.detailData.tem.split(/\//)
                    // console.log(this.tem,this.sugar);
                }
                // console.log('productDetail res',res);
            }).catch(err =>{
                console.log('err=>',err);
            })
            
        },
        // 收藏商品
        likeOrNotlike(){
            let url='';
            if(this.isLike){
               url='/notlike'
            }else{
                url='/like'
            }
                this.axios({
                method:'post',
                url,
                data:{
                    pid:this.pID,
                }
            }).then(res=>{
                console.log('res',res);
                if(res.data.code==700){
                    this.$toast(res.data.msg)
                    setTimeout(()=>{
                        this.$router.push({name:'Login'})
                    },1500)
                }
                 this.$toast(res.data.msg);
                 if(res.data.code===800){
                     this.isLike = true;
                 }else if(res.data.code===900 && res.data.result===1){
                     this.isLike = false
                 }
            }).catch(err=>{
                console.log('err',err);
            })
        },
        // 查询用户是否已收藏该商品
        findUserLike(){
                this.axios({
                method:'get',
                url:'/findlike',
                params:{
                    pid:this.pID,
                }
            }).then(res=>{
                // console.log('findUserLike--res==>',res);
                if(res.data.code===1000 && res.data.result.length===1){
                    // 该商品已被收藏
                    this.isLike=true
                }
            }).catch(err=>{
                console.log('err',err);
            })
        },
        // 加入购物袋
        addShopBag(){
            this.isOver=0;
            let rules=[]
            // 获取商品规格
            console.log('detailData.rules',this.detailData.rules);
            this.detailData.rules.forEach(v=>{
                rules.push(v.rules[v.activeIndex].title);
            })
                console.log('rules',rules);

                 this.axios({
                method:'post',
                url:'/addShopcart',
                data:{
                    pid:this.pID,
                    count:this.count,
                    rule:rules.join('/')
                }
            }).then(res=>{
                console.log('加购res==>',res);
                 if(res.data.code==700){
                    this.$toast(res.data.msg)
                    // 700是未登录 跳转到登录页
                   setTimeout(()=>{
                        this.$router.push({name:'Login'})
                    },1500)
                }
                 this.$toast(res.data.msg);
                 if(res.data.code===3000){
                    this.shopBag+=this.count;
                    this.sid=res.data.sid
                    this.isOver=1;
                }
            }).catch(err=>{
                console.log('err',err);
            })
        },
        // 点击立即购买 先把商品添加到购物车，拿到它sid， 然后把它的checked勾选上，跳转至结算页面
        buyNow(){
            this.addShopBag();
             let timer= setInterval(() => {
                if(this.isOver==1){
                    this.$router.push({name:'Shopbag',params:{sid:this.sid}})
                    clearInterval(timer)
                }
                console.log('定时器--',33333);
            }, 500);
        },
        // 查询用户的购物袋数量
        findUserShopbagCount(){
             this.axios({
                method:'get',
                url:'/shopcartCount',
               
            }).then(res=>{
                // console.log('findUserShopbagCount.res',res);
                if(res.data.code===4000){
                    this.shopBag=res.data.result
                }
            }).catch(err=>{
                console.log('err',err);
            })
        }
    }
}
</script>
<style lang="less" scoped>
@color:#0C34BA;
    .likeActive{
        color: #0c34ba;
    }
    .sitting{
        height: 50px;
    }
    .back-nav-box{
        z-index: 9;
        position: sticky;
        top: 0;
    }
    hr{
        margin: 15px 0;
        background-color: #e8e8e8;
        height: 1px;
        border: none;
    }
    .detail{
        // 描述
        .describe{
            .desc-title{
                font-size: 14px;
            }
            .desc-content{
                margin-top: 10px;
                .desc-content-item{
                    font-size: 12px;
                    color: #555;
                }
            }
        }
        // 数量
        .select-count{
            // background-color: aquamarine;
            display: flex;
            justify-content: space-between;
            font-size: 14px;
            /deep/.van-stepper--round .van-stepper__minus{
                color: @color;
                border-color: @color;
            }  
            /deep/.van-stepper--round .van-stepper__plus{
                background-color: @color;
            }
        }
        .zh-name{
            font-size: 18px;
        }
        .en-name{
            color: #999;
            font-size: 14px;
        }
        .pro-price{
            margin-left: auto;
            font-size: 14px;
            color: @color;
            font-weight: bold;
        }
        .pro-info{
            display: flex;
            align-items: center;
        }
        .detail-content{
            margin: 0 10px;
            padding: 10px;
            background-color: #fff;
            position: relative;
            top: -20px;
            border-top-left-radius: 10px;
            border-top-right-radius: 10px;
           
        }
        .detail-img{
            background-color: #e8e8e8;
        }
        // 规格
         .pro-rule{
            margin-top: 30px;
            .pro-rule-item{
                display: flex;
                align-items: center;
                margin-bottom: 10px;
                &:last-child{
                    margin-bottom: 0px;
                }
                .pro-rule-title{
                    width: 50px;
                    height: 24px;
                    line-height: 24px;
                    font-size: 14px;
                   
                }
                .pro-sub-rule{
                    display: flex;
                    .pro-sub-rule-item{
                        width: 60px;
                        background-color: #e8e8e8;
                        height: 24px;
                        line-height: 24px;
                        text-align: center;
                        margin-right: 10px;
                        border-radius: 12px;
                        font-size: 14px;
                        &:last-child{
                            margin-right: 0px;
                        }
                        &.active{
                            background-color: @color;
                            color: #fff;
                        }
                    }
                }
            }     
        }
    }
</style>